<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 100%;
      height: 5000px;
      position: relative;
    }

    #show{
      width: 200px;
      height: 200px;
      position: absolute;
      top: 1400px;
      background: #ffffff;
    }
  </style>
</head>

<body>

  <div class="box">
    <div id="show"></div>
  </div>

  <script>

    function getRandomColor() {
      const letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }

    window.onload = function () {
      // 添加20个div元素
      // 每个元素随机颜色，高度250px
      for (let i = 0; i < 20; i++) {
        const div = document.createElement('div');
        div.style.backgroundColor = getRandomColor();
        div.style.height = '250px';
        div.style.width = '100%';
        document.querySelector('.box').appendChild(div);
      }
    }


    window.addEventListener('scroll', () => {
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      const clientHeight = document.documentElement.clientHeight; // clientHeight是可见部分的高度
      const scrollHeight = document.documentElement.scrollHeight; // scrollHeight是整个页面的高度，包括不可见部分
      // console.log(scrollTop, clientHeight, scrollHeight);

      if (scrollTop + clientHeight >= scrollHeight - 50) {
        // 触发加载更多
        // loadMoreData();
        console.log('加载更多数据...');
      }
    });

    const observer = new IntersectionObserver((entries) => {
      console.log(entries); // entries是一个数组，包含了所有被观察的元素的交叉状态
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          console.log('元素进入视口');
        } else {
          console.log('元素离开视口');
        }
      });
    });

    const el = document.querySelector('#show');
    observer.observe(el);

  </script>
</body>

</html>